<template>
  <el-form :model="form" label-width="100px" @submit.native.prevent>
    <template v-if="useDynamicInputs">
      <el-form-item v-for="(key, index) in filteredKeys" :key="key" :label="key">
        <el-input
          ref="inputRefs"
          v-model="form.html[key]"
          type="textarea"
          :rows="expandedKey === key ? 10 : 1"
          @focus="onFocus(key)"
          @blur="onBlur"
          @keydown.native.down.prevent="onKeyDownDown(index)"
        />
      </el-form-item>
    </template>
  </el-form>
</template>

<script>
export default {
  name: 'AdBuildForm',
  props: {
    form: {
      type: Object,
      required: true
    },
    configResult: String,
    useDynamicInputs: {
      type: Boolean,
      default: true
    },
    isExample: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      expandedKey: null
    }
  },
  computed: {
    filteredKeys() {
      return Object.keys(this.form.html || {}).filter(key => !key.startsWith('hd'))
    }
  },
  mounted() {
    if (this.filteredKeys.length > 0 && this.useDynamicInputs) {
      this.expandedKey = this.filteredKeys[0]
      this.$nextTick(() => {
        this.focusInputByIndex(0)
      })
    }
  },
  methods: {
    onFocus(key) {
      this.expandedKey = key
    },
    onBlur() {
      this.expandedKey = null
    },
    focusInputByIndex(index) {
      const input = this.$refs.inputRefs[index]
      if (input && input.$el) {
        const textarea = input.$el.querySelector('textarea')
        if (textarea) textarea.focus()
      }
    },
    onKeyDownDown(currentIndex) {
      const nextIndex = (currentIndex + 1) % this.filteredKeys.length
      this.expandedKey = this.filteredKeys[nextIndex]
      this.$nextTick(() => {
        this.focusInputByIndex(nextIndex)
      })
    }
  }
}
</script>
